// 本地聊天数据存储服务 - 替代后端/service/chat接口
// 此文件提供完整的localStorage方案，方便调试和测试

export interface LocalChatMessage {
  id: string;
  sender_id: string;
  recipient_id: string;
  message_type: string;
  content: string;
  timestamp: string;
  status: string;
  conversation_id: string;
}

export interface LocalConversationState {
  _id: string;
  c_user_id: string;
  b_user_id: string;
  conversation_id: string;
  last_message_content: string;
  last_message_time: string;
  c_user_unread_count: number;
  b_user_unread_count: number;
  created_at: string;
  updated_at: string;
}

// localStorage键名
const STORAGE_KEYS = {
  CONVERSATIONS: 'chat_conversations',
  MESSAGES: 'chat_messages',
  MESSAGE_COUNTER: 'chat_message_counter'
} as const;

// 消息变化监听器类型
type MessageChangeListener = (conversationId: string, message: LocalChatMessage) => void;
type ConversationUpdateListener = (conversations: LocalConversationState[]) => void;

class LocalChatStorageService {
  private messageChangeListeners: MessageChangeListener[] = [];
  private conversationUpdateListeners: ConversationUpdateListener[] = [];
  private messageCounter: number = 0;

  constructor() {
    this.initializeStorage();
    this.messageCounter = this.getMessageCounter();
  }

  // 初始化存储，创建默认数据
  private initializeStorage() {
    if (!localStorage.getItem(STORAGE_KEYS.CONVERSATIONS)) {
      localStorage.setItem(STORAGE_KEYS.CONVERSATIONS, JSON.stringify([]));
    }
    if (!localStorage.getItem(STORAGE_KEYS.MESSAGES)) {
      localStorage.setItem(STORAGE_KEYS.MESSAGES, JSON.stringify({}));
    }
    if (!localStorage.getItem(STORAGE_KEYS.MESSAGE_COUNTER)) {
      localStorage.setItem(STORAGE_KEYS.MESSAGE_COUNTER, '1');
    }
  }

  // 获取消息计数器
  private getMessageCounter(): number {
    const counter = localStorage.getItem(STORAGE_KEYS.MESSAGE_COUNTER);
    return counter ? parseInt(counter, 10) : 1;
  }

  // 更新消息计数器
  private updateMessageCounter() {
    this.messageCounter++;
    localStorage.setItem(STORAGE_KEYS.MESSAGE_COUNTER, this.messageCounter.toString());
  }

  // 生成唯一消息ID
  private generateMessageId(): string {
    this.updateMessageCounter();
    return `msg_${Date.now()}_${this.messageCounter}`;
  }

  // 生成会话ID (保持localStorage的存储格式)
  generateConversationId(bUserId: string, cUserId: string): string {
    return `conv_${bUserId}_${cUserId}`;
  }

  // 获取所有会话列表
  getConversations(): LocalConversationState[] {
    try {
      const data = localStorage.getItem(STORAGE_KEYS.CONVERSATIONS);
      return data ? JSON.parse(data) : [];
    } catch (error) {
      console.error('Error loading conversations from localStorage:', error);
      return [];
    }
  }

  // 保存会话列表
  private saveConversations(conversations: LocalConversationState[]) {
    try {
      localStorage.setItem(STORAGE_KEYS.CONVERSATIONS, JSON.stringify(conversations));
      this.notifyConversationUpdate(conversations);
    } catch (error) {
      console.error('Error saving conversations to localStorage:', error);
    }
  }

  // 获取所有消息数据
  private getMessagesData(): Record<string, LocalChatMessage[]> {
    try {
      const data = localStorage.getItem(STORAGE_KEYS.MESSAGES);
      return data ? JSON.parse(data) : {};
    } catch (error) {
      console.error('Error loading messages from localStorage:', error);
      return {};
    }
  }

  // 保存消息数据
  private saveMessagesData(messagesData: Record<string, LocalChatMessage[]>) {
    try {
      localStorage.setItem(STORAGE_KEYS.MESSAGES, JSON.stringify(messagesData));
    } catch (error) {
      console.error('Error saving messages to localStorage:', error);
    }
  }

  // 获取指定会话的消息历史
  getConversationMessages(conversationId: string): LocalChatMessage[] {
    const messagesData = this.getMessagesData();
    return messagesData[conversationId] || [];
  }

  // 添加新消息
  addMessage(message: Omit<LocalChatMessage, 'id'>): LocalChatMessage {
    const newMessage: LocalChatMessage = {
      ...message,
      id: this.generateMessageId()
    };

    const messagesData = this.getMessagesData();
    const { conversation_id } = newMessage;

    if (!messagesData[conversation_id]) {
      messagesData[conversation_id] = [];
    }

    // 检查重复消息
    const isDuplicate = messagesData[conversation_id].some(msg => 
      msg.content === newMessage.content &&
      msg.sender_id === newMessage.sender_id &&
      Math.abs(new Date(msg.timestamp).getTime() - new Date(newMessage.timestamp).getTime()) < 1000
    );

    if (!isDuplicate) {
      messagesData[conversation_id].push(newMessage);
      this.saveMessagesData(messagesData);
      
      // 更新会话状态
      this.updateConversationAfterMessage(newMessage);
      
      // 通知消息监听器
      this.notifyMessageChange(conversation_id, newMessage);
    }

    return newMessage;
  }

  // 消息发送后更新会话状态
  private updateConversationAfterMessage(message: LocalChatMessage) {
    const conversations = this.getConversations();
    const { conversation_id, sender_id, content, timestamp } = message;
    
    let targetConversation = conversations.find(conv => conv.conversation_id === conversation_id);
    
    if (!targetConversation) {
      // 从会话ID中提取B端用户ID
      const bUserId = this.extractBUserIdFromConversationId(conversation_id);
      
      // 创建新会话
      targetConversation = {
        _id: `${conversation_id}_state`,
        c_user_id: sender_id === bUserId ? message.recipient_id : sender_id,
        b_user_id: bUserId,
        conversation_id: conversation_id,
        last_message_content: content,
        last_message_time: timestamp,
        c_user_unread_count: sender_id === bUserId ? 0 : 1,
        b_user_unread_count: sender_id === bUserId ? 0 : 1,
        created_at: timestamp,
        updated_at: timestamp
      };
      conversations.push(targetConversation);
    } else {
      // 更新现有会话
      targetConversation.last_message_content = content;
      targetConversation.last_message_time = timestamp;
      targetConversation.updated_at = timestamp;
      
      // 更新未读计数
      if (sender_id === targetConversation.b_user_id) {
        // B端发送消息，重置B端未读，不影响C端未读
        targetConversation.b_user_unread_count = 0;
      } else {
        // C端发送消息，增加B端未读
        targetConversation.b_user_unread_count++;
      }
    }
    
    this.saveConversations(conversations);
  }

  // 从会话ID中提取B端用户ID
  private extractBUserIdFromConversationId(conversationId: string): string {
    // 会话ID格式：conv_B_UserId_CUserId
    const parts = conversationId.split('_');
    if (parts.length >= 3) {
      return parts[1] + '_' + parts[2]; // 重建B_UserId格式
    }
    return 'B_Admin001'; // 默认值，用于兼容旧数据
  }

  // 标记会话为已读
  markConversationRead(conversationId: string, userId?: string): boolean {
    try {
      const conversations = this.getConversations();
      const targetConversation = conversations.find(conv => conv.conversation_id === conversationId);
      
      if (targetConversation) {
        // 如果没有指定userId，从会话中获取B端用户ID
        const bUserId = userId || targetConversation.b_user_id;
        
        if (bUserId === targetConversation.b_user_id) {
          targetConversation.b_user_unread_count = 0;
        } else {
          targetConversation.c_user_unread_count = 0;
        }
        targetConversation.updated_at = new Date().toISOString();
        
        this.saveConversations(conversations);
        return true;
      }
      return false;
    } catch (error) {
      console.error('Error marking conversation as read:', error);
      return false;
    }
  }

  // 创建或获取会话
  getOrCreateConversation(bUserId: string, cUserId: string): LocalConversationState {
    const conversationId = this.generateConversationId(bUserId, cUserId);
    const conversations = this.getConversations();
    
    let conversation = conversations.find(conv => conv.conversation_id === conversationId);
    
    if (!conversation) {
      conversation = {
        _id: `${conversationId}_state`,
        c_user_id: cUserId,
        b_user_id: bUserId,
        conversation_id: conversationId,
        last_message_content: '',
        last_message_time: new Date().toISOString(),
        c_user_unread_count: 0,
        b_user_unread_count: 0,
        created_at: new Date().toISOString(),
        updated_at: new Date().toISOString()
      };
      
      conversations.push(conversation);
      this.saveConversations(conversations);
    }
    
    return conversation;
  }

  // 模拟WebSocket消息接收（用于测试）
  simulateIncomingMessage(senderId: string, recipientId: string, content: string, bUserId: string): LocalChatMessage {
    const conversationId = this.generateConversationId(bUserId, senderId === bUserId ? recipientId : senderId);
    
    return this.addMessage({
      sender_id: senderId,
      recipient_id: recipientId,
      message_type: 'text',
      content: content,
      timestamp: new Date().toISOString(),
      status: 'sent',
      conversation_id: conversationId
    });
  }

  // 清空所有数据（用于测试重置）
  clearAllData() {
    localStorage.removeItem(STORAGE_KEYS.CONVERSATIONS);
    localStorage.removeItem(STORAGE_KEYS.MESSAGES);
    localStorage.removeItem(STORAGE_KEYS.MESSAGE_COUNTER);
    this.initializeStorage();
    this.messageCounter = 1;

  }

  // 导出数据（用于调试）
  exportData() {
    return {
      conversations: this.getConversations(),
      messages: this.getMessagesData(),
      messageCounter: this.messageCounter
    };
  }

  // 导入数据（用于测试）
  importData(data: { conversations?: LocalConversationState[], messages?: Record<string, LocalChatMessage[]> }) {
    if (data.conversations) {
      localStorage.setItem(STORAGE_KEYS.CONVERSATIONS, JSON.stringify(data.conversations));
    }
    if (data.messages) {
      localStorage.setItem(STORAGE_KEYS.MESSAGES, JSON.stringify(data.messages));
    }

  }

  // 消息变化监听器管理
  addMessageChangeListener(listener: MessageChangeListener) {
    this.messageChangeListeners.push(listener);
  }

  removeMessageChangeListener(listener: MessageChangeListener) {
    const index = this.messageChangeListeners.indexOf(listener);
    if (index > -1) {
      this.messageChangeListeners.splice(index, 1);
    }
  }

  private notifyMessageChange(conversationId: string, message: LocalChatMessage) {
    this.messageChangeListeners.forEach(listener => listener(conversationId, message));
  }

  // 会话更新监听器管理  
  addConversationUpdateListener(listener: ConversationUpdateListener) {
    this.conversationUpdateListeners.push(listener);
  }

  removeConversationUpdateListener(listener: ConversationUpdateListener) {
    const index = this.conversationUpdateListeners.indexOf(listener);
    if (index > -1) {
      this.conversationUpdateListeners.splice(index, 1);
    }
  }

  private notifyConversationUpdate(conversations: LocalConversationState[]) {
    this.conversationUpdateListeners.forEach(listener => listener(conversations));
  }

  // 获取统计信息（用于调试）
  getStats() {
    const conversations = this.getConversations();
    const messagesData = this.getMessagesData();
    const totalMessages = Object.values(messagesData).reduce((sum, msgs) => sum + msgs.length, 0);
    
    return {
      totalConversations: conversations.length,
      totalMessages: totalMessages,
      unreadConversations: conversations.filter(conv => conv.b_user_unread_count > 0).length,
      totalUnreadMessages: conversations.reduce((sum, conv) => sum + conv.b_user_unread_count, 0)
    };
  }
}

// 导出单例服务
export const localChatStorage = new LocalChatStorageService();

// 开发调试工具（仅在开发环境下暴露到全局）
if (process.env.NODE_ENV === 'development') {
  (window as any).localChatStorage = localChatStorage;
} 